/**
 * ClassName:MyApp.java
 * PackageName:com.shopnc_local_life.android.common
 * Create On 2017-10-16下午4:52:02
 * Site:http://weibo.com/hjgang or http://t.qq.com/hjgang_
 * EMAIL:hjgang@bizpower.com or hjgang@yahoo.cn
 * Copyrights 2017-10-16 liming All rights reserved.
 */
package com.meihua.baoleyi.common;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.RadioButton;
import android.widget.TabHost;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.widget.CallDialog;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;


public class MyApp extends Application {
    /**
     * 系统初始化配置文件操作器
     */
    private SharedPreferences sysInitSharedPreferences;
    /**
     * 记录默认城市名称
     */
    private String city_id;
    private String city_name;
    private boolean city_id_flag;
    private String member_id;
    private String member_key;
    private String first_start_flag;

    private static int screenWidth;

    private static int screenHeight;

    private String Photo_path;

    private TabHost tabHost;
    private RadioButton btn_test2;
    private AccountManager am;
    private Account[] accounts;
    private String Ticket = "ticket";
    private String name;
    private String company;
    private String homee;
    private String companyy;
    private String origin;
    private String end;
    private int milege;
    private String Userid = "userid";
    private String areaid;
    // private String Communityid="communityid";
    private String Mobile = "mobile";
    private String UserName = "username";
    public static List<RunningAppProcessInfo> atlist;
    public static Context applicationContext;
    private static MyApp instance;
    // login user name
    public final String PREF_USERNAME = "username";
    public String message;
    public String messaget;
    //	public Typeface typeface;
//	public List<EmojiBean> iterator;
    public boolean RESULT_FROM_VIEW_PHOTOS = false;

    private String Thirdid = "thirdid";                                                    //第三方的鹰眼Id
    private String UserNick = "userNick";                                                //支付的方式
    private String ThirdId = "thirdid";
    private String AuccontName = "com.youqin";

    private String Lat, Lng, loginBy; //当前城市的经纬度
    public Long time;

    private String Token, User_id, Real_name, Uname, Phone;
    private int level;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 当前用户nickname,为了苹果推送不是userid而是昵称
     */
    public static String currentUserNick = "";

    // public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
//		MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化Prefs
        PrefsHelper.init(this);
        //极光初始化
        JPushInterface.init(this);
        //必须调用初始化
        OkGo.init(this);
        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            //以下都不是必须的，根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
            OkGo.getInstance()

                    //打开该调试开关,控制台会使用 红色error 级别打印log,并不是错误,是为了显眼,不需要就不要加入该行
                    .debug("OkGo")

                    //如果使用默认的 60秒,以下三行也不需要传
                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS)  //全局的连接超时时间
                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间

                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                    .setCacheMode(CacheMode.NO_CACHE);

            //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
//					.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)

            //如果不想让框架管理cookie,以下不需要
//                .setCookieStore(new MemoryCookieStore())                //cookie使用内存缓存（app退出后，cookie消失）
//					.setCookieStore(new PersistentCookieStore())          //cookie持久化存储，如果cookie不过期，则一直有效

            //可以设置https的证书,以下几种方案根据需要自己设置,不需要不用设置
//                    .setCertificates()                                  //方法一：信任所有证书
//                    .setCertificates(getAssets().open("srca.cer"))      //方法二：也可以自己设置https证书
//                    .setCertificates(getAssets().open("aaaa.bks"), "123456", getAssets().open("srca.cer"))//方法三：传入bks证书,密码,和cer证书,支持双向加密

            //可以添加全局拦截器,不会用的千万不要传,错误写法直接导致任何回调不执行
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        return chain.proceed(chain.request());
//                    }
//                })

//					//这两行同上,不需要就不要传
//					.addCommonHeaders(headers)                                         //设置全局公共头
//					.addCommonParams(params);                                          //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }

        Constants.init(this);
        // JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
        // JPushInterface.init(this); // 初始化 JPush
        sysInitSharedPreferences = getSharedPreferences(Constants.SYSTEM_INIT_FILE_NAME, MODE_PRIVATE);
        am = AccountManager.get(this);
        DisplayMetrics dm = SystemHelper.getScreenInfo(this);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        applicationContext = this;
        instance = this;

        //应用程序的上下文
        applicationContext = getApplicationContext();


//		LocalImageHelper.init(this);
        /**
         * 异步加载图片
         */
//		File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache");
        File cacheDir = new File(Constants.CACHE_DIR, "imageloader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(applicationContext).memoryCacheExtraOptions(480, 800) // max
                // width,
                // max
                // height，即保存的每个缓存文件的最大长宽
                .discCacheExtraOptions(480, 800, null) // Can slow ImageLoader,
                // use it carefully
                // (Better don't use
                // it)/设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(10)// 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You
                // can
                // pass
                // your
                // own
                // memory
                // cache
                // implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024).discCacheSize(50 * 1024 * 1024).discCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                // 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO).discCacheFileCount(100) // 缓存的文件数量
                .discCache(new UnlimitedDiskCache(cacheDir))// 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()).imageDownloader(new BaseImageDownloader(applicationContext, 5 * 1000, 30 * 1000)) // connectTimeout
                // s)超时时间
                .writeDebugLogs() // Remove for release app
                .build();// 开始构建
//		iterator = EmojiGetter.readXML(this);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);// 全局初始化此配置
    }

    public static Context getContext() {
        return applicationContext;
    }

    public static MyApp getInstance() {
        return instance;
    }


    public static int getScreenWidth() {
        return screenWidth;
    }


    public void setUserLogin(String mobile, String pass, String ticket, String userid) {
        if (accounts != null) {
            if (accounts.length == 0) {
                Account ac = new Account(mobile, getString(R.string.account_type));
                Bundle userdata = new Bundle();
                userdata.putString(Ticket, ticket);
                userdata.putString(Userid, userid);
                userdata.putString(Mobile, mobile); //
                userdata.putString(UserName, pass);
                am.addAccountExplicitly(ac, pass, userdata);
            } else {
                am.setUserData(accounts[0], Ticket, ticket);
            }
        }
    }


    public void setUserLogin(String mobile, String pass, String ticket, String userid, String thirdid, String userNick) {
        if (accounts != null) {
            if (accounts.length == 0) {
                Account ac = new Account(mobile, AuccontName);
                Bundle userdata = new Bundle();
                userdata.putString(Ticket, ticket);
                userdata.putString(Userid, userid);
                userdata.putString(Mobile, mobile);
                userdata.putString(UserName, pass);
                userdata.putString(Thirdid, thirdid);
                userdata.putString(UserNick, userNick);
                userdata.putString(ThirdId, thirdid);
                am.addAccountExplicitly(ac, pass, userdata);
            } else {
                am.setUserData(accounts[0], Ticket, ticket);
            }
        }
    }

    public static void editorString(String key, String value, Context context) {
        SharedPreferences.Editor editor = context.getSharedPreferences("userInfo", Activity.MODE_PRIVATE).edit();
        editor.putString(key, value);
        editor.commit();
    }


    public String getToken() {
        return sysInitSharedPreferences.getString("token", "");
    }

    public void setToken(String token) {
        this.Token = token;
        sysInitSharedPreferences.edit().putString("token", this.Token).commit();
    }


    public String getUser_id() {
        return sysInitSharedPreferences.getString("id", "");
    }

    public void setUser_id(String user_id) {
        this.User_id = user_id;
        sysInitSharedPreferences.edit().putString("id", this.User_id).commit();

    }

    public String getAvatar() {
        return sysInitSharedPreferences.getString("avatar", "");
    }

    public void setAvatar(String avatar) {
        sysInitSharedPreferences.edit().putString("avatar", avatar).commit();
    }

    private List<BaseActivity> activities = new ArrayList<>();

    public void addActivity(BaseActivity activity) {
        if (!activities.contains(activity)) activities.add(activity);
    }

    public void removeActivity(BaseActivity activity) {
        activities.remove(activity);
    }

    public void exit() {
        if (activities != null && activities.size() > 0) {
            for (BaseActivity activity : activities) {
                activity.finish();
            }
        }
    }

    public String getReal_name() {
        return sysInitSharedPreferences.getString("real_name", "");
    }

    public void setReal_name(String real_name) {
        this.Real_name = real_name;
        sysInitSharedPreferences.edit().putString("real_name", this.Real_name).commit();
    }

    public String getUname() {
        return sysInitSharedPreferences.getString("uname", "");
    }

    public void setUname(String uname) {
        this.Uname = uname;
        sysInitSharedPreferences.edit().putString("uname", this.Uname).commit();
    }

    public String getPhone() {
        return sysInitSharedPreferences.getString("phone", "");
    }

    public void setPhone(String phone) {
        this.Phone = phone;
        sysInitSharedPreferences.edit().putString("phone", this.Phone).commit();
    }


    public String getLat() {
        return sysInitSharedPreferences.getString("lat", "");
    }

    public void setLat(String lat) {
        this.Lat = lat;
        sysInitSharedPreferences.edit().putString("lat", this.Lat).commit();
    }

    public String getLng() {
        return sysInitSharedPreferences.getString("lng", "");
    }

    public void setLng(String lng) {
        this.Lng = lng;
        sysInitSharedPreferences.edit().putString("lng", this.Lng).commit();
    }

    public String getLoginBy() {
        return sysInitSharedPreferences.getString("by", "");
    }

    public void setLoginBy(String by) {
        this.loginBy = by;
        sysInitSharedPreferences.edit().putString("by", this.loginBy).commit();
    }

    public String getName() {
        return sysInitSharedPreferences.getString("name", "");
    }

    public void setName(String name) {
        this.name = name;
        sysInitSharedPreferences.edit().putString("name", this.name).commit();
    }


    public String getCompany() {
        return sysInitSharedPreferences.getString("company", "");
    }

    public void setCompany(String company) {
        this.company = company;
        sysInitSharedPreferences.edit().putString("company", this.company).commit();
    }


    public String getOrigin() {
        return sysInitSharedPreferences.getString("origin", "");
    }

    public void setOrigin(String origin) {
        this.origin = origin;
        sysInitSharedPreferences.edit().putString("origin", this.origin).commit();
    }


    public String getEnd() {
        return sysInitSharedPreferences.getString("end", "");
    }

    public void setEnd(String end) {
        this.end = end;
        sysInitSharedPreferences.edit().putString("end", this.end).commit();
    }


//	public String getHomee() {
//		return sysInitSharedPreferences.getString("homee", "");
//	}
//
//	public void setHomee(String homee) {
//		this.homee = homee;
//		sysInitSharedPreferences.edit().putString("homee", this.homee).commit();
//	}
//
//
//
//	public String getCompanyy() {
//		return sysInitSharedPreferences.getString("companyy", "");
//	}
//
//	public void setCompanyy(String companyy) {
//		this.companyy = companyy;
//		sysInitSharedPreferences.edit().putString("companyy", this.companyy).commit();
//	}
//


    public String getAreaid() {
        return sysInitSharedPreferences.getString("areaid", "");
    }

    public void setAreaid(String areaid) {
        this.areaid = areaid;
        sysInitSharedPreferences.edit().putString("areaid", this.areaid).commit();
    }

    public String getMessage() {
        return sysInitSharedPreferences.getString("message", "");
    }

    public void setMessage(String message) {
        this.message = message;
        sysInitSharedPreferences.edit().putString("message", this.message).commit();
    }

    public String getMessageT() {
        return sysInitSharedPreferences.getString("messaget", "");
    }

    public void setMessageT(String messaget) {
        this.messaget = messaget;
        sysInitSharedPreferences.edit().putString("messaget", this.messaget).commit();
    }

    // public void setName(String name) {
    // if (accounts.length == 0) {
    // Account ac = new Account(name, getString(R.string.account_type));
    // Bundle userdata1 = new Bundle();
    // userdata1.putString(Name, name);
    // am.addAccountExplicitly(ac, null, userdata1);
    // } else {
    // am.setUserData(accounts[0], Name, name);
    // }
    // }
    //


    // 获得手机号
    public String getUserMobile() {
        String mob = "";
        accounts = am.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            mob = am.getUserData(accounts[0], Mobile);
            if (mob == null) {
                mob = "";
            }
        }
        return mob;
    }

    public String getUserTicket() {
        String ret = "";
        accounts = am.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            ret = am.getUserData(accounts[0], Ticket);
            if (ret == null) {
                ret = "";
            }
        }
        return ret;
    }

    public String getUserId() {
        String ret = "";
        accounts = am.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            ret = am.getUserData(accounts[0], Userid);
            if (ret == null) {
                ret = "";
            }
        }
        return ret;
    }

    public String getUserName() {
        String ret = "";
        accounts = am.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            ret = am.getUserData(accounts[0], UserName);
            if (ret == null) {
                ret = "";
            }
        }
        return ret;
    }


    public void logout() {
        accounts = am.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            am.removeAccount(accounts[0], null, null);
//			new AddaliasTask(getUserId() + "sxl", "sxl_type");
        }
    }

    /**
     * 判断用户是否登录，未登录跳到登录界面
     */
    public boolean isLogin(Context activity) {
        String token = getUserTicket();
        if (TextUtils.isEmpty(token)) {
            CallDialog islogin = new CallDialog((Activity) activity, "你尚未登录，是否登录？");
            return false;
        }
        return true;
    }
//	class AddaliasTask extends AsyncTask<Void, Void, Boolean> {
//
//		String alias;
//		String alias_type;
//
//		public AddaliasTask(String alias, String alias_type) {
//			super();
//			this.alias = alias;
//			this.alias_type = alias_type;
//		}

//		@Override
//		protected Boolean doInBackground(Void... params) {
//			boolean result = false;
//			try {
//				result = mPushAgent.removeAlias(alias, alias_type);
//			} catch (JSONException e) {
//				e.printStackTrace();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			return result;
//		}
//
//		@Override
//		protected void onPostExecute(Boolean result) {
//			super.onPostExecute(result);
//		}
//
//	}

    public String getFirst_start_flag() {
        return first_start_flag;
    }

    public void setFirst_start_flag(String first_start_flag) {
        this.first_start_flag = first_start_flag;
        sysInitSharedPreferences.edit().putString("first_start_flag", this.first_start_flag).commit();
    }

    public RadioButton getBtn_test2() {
        return btn_test2;
    }

    public void setBtn_test2(RadioButton btn_test2) {
        this.btn_test2 = btn_test2;
    }

    public TabHost getTabHost() {
        return tabHost;
    }

    public void setTabHost(TabHost tabHost) {
        this.tabHost = tabHost;
    }

    // public void setSearch_dao(SearchDao search_dao) {
    // this.search_dao = search_dao;
    // }

    public void setScreenWidth(int screenWidth) {
        MyApp.screenWidth = screenWidth;
    }

    public static int getScreenHeight() {
        return screenHeight;
    }

    public void setScreenHeight(int screenHeight) {
        MyApp.screenHeight = screenHeight;
    }

    public String getCity_id() {
        return city_id;
    }

    public String getPhoto_path() {
        return Photo_path;
    }

    public void setPhoto_path(String photo_path) {
        Photo_path = photo_path;
        sysInitSharedPreferences.edit().putString("Photo_path", this.Photo_path).commit();
    }

    public void setCity_id(String city_id) {
        this.city_id = city_id;
        sysInitSharedPreferences.edit().putString("city_id", this.city_id).commit();
    }

    public String getMember_id() {
        return member_id;
    }

    public void setMember_id(String member_id) {
        this.member_id = member_id;
        sysInitSharedPreferences.edit().putString("member_id", this.member_id).commit();
    }

    public String getMember_key() {
        return member_key;
    }

    public void setMember_key(String member_key) {
        this.member_key = member_key;
        sysInitSharedPreferences.edit().putString("member_key", this.member_key).commit();
    }

    public String getCity_name() {
        return city_name;
    }

    public void setCity_name(String city_name) {
        this.city_name = city_name;
        sysInitSharedPreferences.edit().putString("city_name", this.city_name).commit();
    }

    public boolean isCity_id_flag() {
        return city_id_flag;
    }

    public void setCity_id_flag(boolean city_id_flag) {
        this.city_id_flag = city_id_flag;
        sysInitSharedPreferences.edit().putBoolean("city_id_flag", this.city_id_flag).commit();
    }

    /**
     * 登录的方式
     */
    //  0 表示乘客    ,1表示车主
    public int getStatus() {
        int status_of_is_driver = sysInitSharedPreferences.getInt("status_of_is_driver", 0);
        return status_of_is_driver;
    }

    //  0 表示乘客    ,1表示车主
    public void setStatus(int status) {
        sysInitSharedPreferences.edit().putInt("status_of_is_driver", status).commit();
    }

    public String getidcard() {
        String idcard = sysInitSharedPreferences.getString("idcard", "");
        return idcard;
    }

    //  0 表示乘客    ,1表示车主
    public void setidcard(String idcard) {
        sysInitSharedPreferences.edit().putString("idcard", idcard).commit();
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    /**
     * 获取系统初始化文件操作器
     *
     * @return
     */
    public SharedPreferences getSysInitSharedPreferences() {
        return sysInitSharedPreferences;
    }

    // 创建SD卡缓存目录
    private void createCacheDir() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File f = new File(Constants.CACHE_DIR);
            if (f.exists()) {
                System.out.println("SD卡缓存目录:已存在!");
            } else {
                if (f.mkdirs()) {
                    System.out.println("SD卡缓存目录:" + f.getAbsolutePath() + "已创建!");
                } else {
                    System.out.println("SD卡缓存目录:创建失败!");
                }
            }
            File ff = new File(Constants.CACHE_IMAGE);
            if (ff.exists()) {
                System.out.println("SD卡照片缓存目录:已存在!");
            } else {
                if (ff.mkdirs()) {
                    System.out.println("SD卡照片缓存目录:" + ff.getAbsolutePath() + "已创建!");
                } else {
                    System.out.println("SD卡照片缓存目录:创建失败!");
                }
            }
            File fff = new File(Constants.CACHE_DIR_IMAGE);
            if (fff.exists()) {
                System.out.println("SD卡缓存目录:已存在!");
            } else {
                if (fff.mkdirs()) {
                    System.out.println("SD卡照片缓存目录:" + fff.getAbsolutePath() + "已创建!");
                } else {
                    System.out.println("SD卡照片缓存目录:创建失败!");
                }
            }

            File ffff = new File(Constants.CACHE_DIR_UPLOADING_IMG);
            if (ffff.exists()) {
                System.out.println("SD卡上传缓存目录:已存在!");
            } else {
                if (ffff.mkdirs()) {
                    System.out.println("SD卡上传缓存目录:" + ffff.getAbsolutePath() + "已创建!");
                } else {
                    System.out.println("SD卡上传缓存目录:创建失败!");
                }
            }
        } else {
            Toast.makeText(MyApp.this, "亲，您的SD不在了，可能有的功能不能用奥，赶快看看吧。", Toast.LENGTH_SHORT).show();
        }
    }


}
